import * as apis from '@/services/SupplyPlanMgr';
import _ from 'lodash';

const Model = {
  namespace: 'SupplyPlanDetailItemsYears',
  state: {
    overAllYears: [new Date().getFullYear()],
    currentYear: new Date().getFullYear(),
    currentMonths: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14'],
  },
  effects: {
    *fetch({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { overAllYears: [] },
      });
      const response = yield call(apis.overAllYearsUsingGET, payload);
      if (response && response.data && response.data.length > 0) {
        let currentYear = null;
        _.each(response.data, x => {
          if (x === `${new Date().getFullYear()}`) currentYear = x;
        });
        yield put({
          type: 'save',
          payload: { overAllYears: response.data, currentYear: currentYear || response.data[0] },
        });
      } else {
        yield put({
          type: 'save',
          payload: {
            overAllYears: [new Date().getFullYear()],
            currentYear: new Date().getFullYear(),
          },
        });
      }

      if (callback) callback(response && response.data ? response.data : []);
    },

    *changeCurrentYear({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { currentYear: payload.currentYear },
      });
      if (callback) callback();
    },
  },
  reducers: {
    changeCurrentMonths(state, action) {
      let { currentMonths } = action.payload;
      if (currentMonths == null || currentMonths.length === 0) {
        currentMonths = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14'];
      }
      return {
        ...state,
        currentMonths,
      };
    },
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
